package com.open.capacity.paper.service.impl;

import com.open.capacity.paper.dao.SuggestDao;
import com.open.capacity.paper.feign.UserFeignClient;
import com.open.capacity.paper.service.SuggestService;
import com.open.capacity.paper.vo.SuggestVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.Suggest;
import com.open.capacity.common.model.SysRole;
import com.open.capacity.common.model.SysUser;
import com.open.capacity.common.web.PageResult;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SuggestServiceImpl extends ServiceImpl<SuggestDao, Suggest> implements SuggestService {

    @Autowired
    private SuggestDao suggestDao;

    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public PageResult<SuggestVo> getSuggestions(Map<String, Object> params) throws ServiceException{
        try {
            if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null) {
                PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);
            }
            List<Suggest> list = suggestDao.findList(params);
            List<SuggestVo> suggestVos = list.stream().map(suggest -> {
                SuggestVo suggestVo = new SuggestVo();
                BeanUtils.copyProperties(suggest, suggestVo);
                SysUser sysUser = userFeignClient.findUserById(suggest.getUserId());
                suggestVo.setUsername(sysUser.getUsername());
                SysRole sysRole = userFeignClient.findById(Long.valueOf(suggest.getSuggestedRole()));
                suggestVo.setSuggestedRoleStr(sysRole.getName());
                return suggestVo;
            }).collect(Collectors.toList());
            PageInfo<SuggestVo> pageInfo = new PageInfo<>(suggestVos);
            PageInfo<Suggest> suggestInfo = new PageInfo<>(list);
            return PageResult.<SuggestVo>builder().data(pageInfo.getList()).code(0).count(suggestInfo.getTotal()).build();
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}
